from classfile.attribute_info import AttributeInfo, LINE_NUMBER_TABLE


class ExceptionTableEntry:
    def __init__(self, startPC, endPC, handlerPC, catchType):
        self.startPC = 0
        self.endPC = 0
        self.handlerPC = 0
        self.catchType = 0

    @staticmethod
    def readExceptionTable(clsReader):
        tableLen = int.from_bytes(clsReader.readU16(), "big")
        exceptionTable = []
        for i in range(tableLen):
            exceptionTable.append(ExceptionTableEntry(clsReader.readU16(), clsReader.readU16(), clsReader.readU16(), clsReader.readU16()))
        return exceptionTable


class CodeAttribute(AttributeInfo):
    def __init__(self, constPool):
        super().__init__()
        self.constPool = constPool
        self.maxStack = 0
        self.maxLocals = 0
        self.code = None
        self.exceptionTables = None
        self.attributes = None

    def readInfo(self, clsReader):
        self.maxStack = int.from_bytes(clsReader.readU16(), "big")
        self.maxLocals = int.from_bytes(clsReader.readU16(), "big")
        codeLen = int.from_bytes(clsReader.readU32(), "big")
        self.code = clsReader.readBytes(codeLen)
        self.exceptionTables = ExceptionTableEntry.readExceptionTable(clsReader)
        self.attributes = AttributeInfo.readAttributes(clsReader, self.constPool)

    def getLineNumberTableAttribute(self):
        for attr in self.attributes:
            if attr.type == LINE_NUMBER_TABLE:
                return attr
        return None

